// pages/subscribe/subscribe.js
let app = getApp()
let request = require('../../utils/request')

let addFlag = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    pageAllHeight: app.globalData.pageAllHeight,
    screenHeight: 0,
    parkId: 0,
    parkInfo: {},
    subscribeRule: [],
    timeTab: [],
    timeTabIndex: 0,
    timeList: [],
    timeListIndex: -1,
    carNumList: [],
    carNumberIndex: 0,
    payMoney: 0,
    haveApplyList: [],
    longitude: 0,
    latitude: 0,
    searchDialog: false,
    searchResult: [],
    searcheVip: [],
    addCarDialog: false,
    activeIptIndex: -1,
    carNo: '',
    inputLen: 8,
    orderTime:60,
    orderTimeState:false,
    setIntervalTime:'',
    showCarMoney:true,
    hiddenReserveMoney:true,
    hiddenDesc:false,
    startTime:'',
    endTime:'',
    showPayButton:true,
    agreementVip: true,
    showAddCar:false,
    showLogin:true,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('参数：', options)
    this.setData({
      screenHeight: wx.getSystemInfoSync().screenHeight
    })

    this.getCode();
    let phoneNumber = wx.getStorageSync('phoneNumber')
    if(phoneNumber) {
      this.setData({
        showLogin : false
      })
    }
  },

  onShow() {
    let token = wx.getStorageSync('token');
    if (token) {
      this.getCarNumList()
    } else {

    }
  },

  // 获取code
  getCode () {
    wx.login({
      success : res => {
        this.setData({
          code: res.code
        })
      }
    })
  },

  // 获取手机号
  getPhoneNumber (e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      console.log(e);
      this.setData({
        encryptedData : e.detail.encryptedData,
        iv : e.detail.iv
      })

      this.getPhoneNum();
    }else{
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入开闸，请授权!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: res => {
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  },

  // 获取手机号
  getPhoneNum () {
    let url = '/customer/info/getMobilePhone'
    let params = {
      code: this.data.code,
      encryptedData: this.data.encryptedData,
      iv: this.data.iv,
    }
    request.http(url, 'GET', params,0).then(res => {
      let data = res.data.data;
      console.log(res);
      if (res.data.code == 200) {
        wx.setStorageSync('phoneNumber', data)
        this.setData({
          phoneNumber: data,
          showLogin:false
        })
        this.getOrder();
      }
    }).catch(err => { console.error(err) })
  },
  /**
  * 查询车牌列表
  */
  getCarNumList() {
    let that = this;
    let url = "/customer/car/getCustomerCarList";
    request.http(url, 'GET')
      .then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          let list = res.data.data;
          if (list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              if (i == 0) {
                list[i]['select'] = true
              } else {
                list[i]['select'] = false
              }
            }
            that.setData({
              carNumList: list
            })
          } else {
            that.setData({
              carNumList: []
            })
          }
        }
      })
  },

  /**
   * 选择车牌号
   */
  selectCar(e) {
    let index = e.currentTarget.dataset.index
    let carList = this.data.carNumList
    for (var i = 0; i < carList.length; i++) {
      carList[i]['select'] = false
    }
    carList[index]['select'] = true
    this.setData({
      carNumList: carList,
      carNumberIndex: index
    })
  },

  async beiguoAddTicket (carNumber) {
    console.log(carNumber);
    let params = { carNumber }
    let url = "/customer/info/beiguoAddTicket";
    const { data : res } = await request.http(url, 'GET',params)
    console.log(res);
    wx.showToast({
      icon:'none', 
      title: res.data 
    })
  },

  searchOrder() {
    let carNumber = this.data.carNumList.length != 0? this.data.carNumList[this.data.carNumberIndex].carNumber : null;
    console.log(carNumber);
    this.beiguoAddTicket(carNumber)
  },

  deleteCarNum(event) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除该车牌号吗？',
      showCancel: true, //是否显示取消按钮
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击确定
          let id = event.currentTarget.dataset.customerid;
          let url = '/customer/car/deleteCustomerCar'
          let params = { id }
          request.http(url, 'POST', params).then((res) => {
            console.log(res);
            that.getCarNumList();
          }).catch(err=>{
            console.log(err);
            wx.showToast({
              title: '删除失败，请重试',
              icon:'none'
            })
          })
        }
      },
    })
  },

  verifyLogin() {
    this.getCarNumList()
  },

  // 显示添加车牌号弹窗
  showAddCarDialog() {
    this.setData({
      addCarDialog: true
    })
  },

  showAddCar() {
    this.setData({
      showPayButton:false,
      showAddCar:true
    })
  },
  /**
   * 隐藏添加车牌号弹窗
   */
  diddenAddCarDialog() {
    this.setData({
      addCarDialog: false
    })
  },
  /**
  * 输入车牌号
  */
  onFocus: function (e) {
    var that = this;
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(that.data.carNo)) {
      inputType = 2;
    }
    that.setData({
      showPlateInput: true,
      inputType: inputType,
      activeIptIndex: that.data.carNo.length
    });
  },
  /**
   * 键盘输入操作
   */
  handlePlateChange(e) {
    let value = e.detail.value;
    let inputLen = this.data.inputLen;
    let type = e.detail.type;
    let carNo = this.data.carNo;
    if (carNo.length < inputLen) {
      carNo += value;
    }
    if (type == 1) {
      this.setData({
        inputType: 2
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
   * 用于点击弹出键盘输入，space为键盘弹出后向上拉取的距离 
   * @param {*} e 
   */
  handleClick(e) {
    /* 150为键盘的高度 */
    let space = -(e.currentTarget.offsetTop - 150);
    /* regExp用于判断当前已输入的车牌号是否是中文，并让键盘显示中文还是英文输入 */
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(this.data.carNo)) {
      inputType = 2;
    }
    this.setData({
      translateSpace: space,
      showPlateInput: true,
      inputType
    })
  },
  /**
   * 键盘隐藏事件
   */
  handleHiddenCarPlate() {
    this.setData({
      showPlateInput: false,
      showPayButton:true,
      showAddCar:false,
      activeIptIndex: -1
    })
  },
  /**
   * 点击键盘上的确定
   */
  handlePlateConfirm() {
    /* isCarPlate用于判断输入的车牌号是否符合规范 */
    if (!this.isCarPlate(this.data.carNo)) {
      wx.showToast({
        title: '请输入正确车牌号',
        icon: 'none'
      })
      return false;
    }
    this.setData({
      translateSpace: 0,
      showPlateInput: false,
      inputType: 1,
      activeIptIndex: -1
    })
  },
  /**
   * 用于键盘输入删除
   */
  handlePlateDelete(e) {
    let carNo = this.data.carNo;
    carNo = carNo.substring(0, carNo.length - 1);
    if (carNo.length == 0) {
      this.setData({
        inputType: 1
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
  * 判断车牌号
  * @param {String} value 车牌号
  */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /**
   * 添加车牌号
   */
  addCarNumber() {
    if (addFlag) {
      return
    }
    let that = this;
    let carNo = that.data.carNo;
    if (!that.isCarPlate(that.data.carNo)) {
      wx.showToast({
        title: '请输入正确车牌号',
        icon: 'none'
      })
      return;
    }
    addFlag = true
    let url = '/customer/car/addCustomerCar'
    let params = {
      carNumber: carNo
    }
    request.http(url, 'POST', params)
      .then((res) => {
        let data = res.data
        if (data.code == 200) {
          console.log(data);
          wx.showToast({ title: '添加成功' })
          that.setData({ 
            carNo: '', 
            showAddCar:false
          })
          that.getCarNumList();
          that.handleHiddenCarPlate()
          that.diddenAddCarDialog()
        } else {
          // wx.showToast({ title: '添加失败，请稍后重试！', icon: 'none' })
        }
        addFlag = false
      }).catch((errMsg) => {
        addFlag = false
      });
  },
    /**
   * 用户协议弹窗
   */
  showAgreement(e) {
    let type = e.currentTarget.dataset.type
    this.setData({
      agreementShow: true,
      agreementType: type
    })
  },

})